package com.jinzhi.jzapi.certificate.controller;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.jinzhi.common.annotation.Log;
import com.jinzhi.common.base.BaseController;
import com.jinzhi.common.type.ApiEnumError;
import com.jinzhi.common.utils.ApiResult;
import com.jinzhi.common.utils.Result;
import com.jinzhi.jzapi.certificate.pojo.ExpertsVo;
import com.jinzhi.jzweb.domain.ExpertsDO;
import com.jinzhi.jzweb.domain.KnowledgePointsDO;
import com.jinzhi.jzweb.domain.MsgTemplateDO;
import com.jinzhi.jzweb.domain.OrganizationNewsDO;
import com.jinzhi.jzweb.service.ExpertsService;
import com.jinzhi.jzweb.service.KnowledgePointsService;
import com.jinzhi.jzweb.service.MsgTemplateService;
import com.jinzhi.jzweb.service.OrganizationNewsService;
import com.jinzhi.sys.domain.UserDO;
import com.jinzhi.sys.service.UserRoleService;
import com.jinzhi.sys.service.UserService;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import java.util.*;

import static com.jinzhi.api.util.TokenTag.TOKEN_TAG;

@Slf4j
@RestController
@RequestMapping("/jzApi/experts")
public class ApiExpertsController extends BaseController {

    @Autowired
    private ExpertsService expertsService;
    @Autowired
    private UserService userService;
    @Autowired
    private UserRoleService userRoleService;
    @Autowired
    private OrganizationNewsService organizationNewsService;
    @Autowired
    private KnowledgePointsService knowledgePointsService;
    @Autowired
    private MsgTemplateService msgTemplateService;

    /**
     * api小程序端-专家列表数据接口
     *
     * @Description: 专家列表信息查询，参数：页码，显示数，站点名称（筛选条件），站点类型 （0考评员，1考务员，2考务技术员，3督导员，4讲师）
     * @Param: [current, number, name, type]
     * @return: com.jinzhi.common.utils.ApiResult<?>
     * @Author: kl
     * @Date: 2020-03-04
     */
    @GetMapping("/selExperts")
    @Log("api小程序端-专家列表数据接口")
    @ApiOperation(value = "api小程序端-专家列表数据接口", httpMethod = "GET", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @Transactional
    public ApiResult<?> selExperts(String current, String number, String name, String type) {
        Map map = new HashMap();
        map.put("name",name);
        if(StringUtils.isNotBlank(type)){
            map.put("type",Integer.parseInt(type));
        }else{
            map.put("type","");
        }
        Page<ExpertsVo> page = expertsService.selectListPage(Integer.parseInt(current), Integer.parseInt(number), map);
        List list = new ArrayList();
        for (int i = 0; i < page.getRecords().size(); i++) {
            ExpertsVo obj = (ExpertsVo) page.getRecords().get(i);
            if (obj.getKpointsId() != null) {
                KnowledgePointsDO knowledgePointsDO = knowledgePointsService.selectById(obj.getKpointsId());
                if (knowledgePointsDO != null) {
                    obj.setKpointsName(knowledgePointsDO.getName());
                }
            }
            list.add(obj);
        }
        page.setRecords(list);
        return ApiResult.success(page);
    }

    /**
     * api小程序端-获取专家申请草稿
     *
     * @Description: 专家信息申请，填入数据库；参数：Token令牌，专家照片，附件路径，邮箱，专家姓名，专家性别，专家身份证号，专家类型，所属单位，知识点Id，
     * 证书概况id，出生年月，民族，学历，专业，政治面貌，职务职称，QQ，学习、工作经历，现居住地,省份，市，区
     * @Param: [token, imgUrl, fileUrl, email, name, sex, idNumber, type, orgName, kpointsId,
     * profileId, dateOfBirth,nation, education, major, politicalAffiliation, officialCapacity, QQ, experience, liveAddress,province，city，district]
     * @return: com.jinzhi.common.utils.ApiResult<?>
     * @Author: kl
     * @Date: 2020-03-06
     */
    @PostMapping("/selCao")
    @Log("api小程序端-专家申请接口")
    @ApiOperation(value = "api小程序端-专家申请接口", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @RequiresAuthentication
    @Transactional
    @ApiImplicitParams({@ApiImplicitParam(name = TOKEN_TAG, value = TOKEN_TAG, paramType = "header")})
    public ApiResult<?> selCao(@RequestHeader(value = TOKEN_TAG, required = false) String token,String type){
        UserDO user = this.getClientUser(token);
        if (null == user) {
            return ApiResult.invalid();
        }
        ExpertsDO expertsDO = null;
        expertsDO = expertsService.findOneByKv("type",Integer.parseInt(type),"user_id",user.getId(),"state",6);
        if(expertsDO==null){
            return ApiResult.success(null);
        }else{
            return ApiResult.success(expertsDO);
        }

    }


    /**
     * api小程序端-专家申请接口
     *
     * @Description: 专家信息申请，填入数据库；参数：Token令牌，专家照片，附件路径，邮箱，专家姓名，专家性别，专家身份证号，专家类型，所属单位，知识点Id，
     * 证书概况id，出生年月，民族，学历，专业，政治面貌，职务职称，QQ，学习、工作经历，现居住地,省份，市，区
     * @Param: [token, imgUrl, fileUrl, email, name, sex, idNumber, type, orgName, kpointsId,
     * profileId, dateOfBirth,nation, education, major, politicalAffiliation, officialCapacity, QQ, experience, liveAddress,province，city，district]
     * @return: com.jinzhi.common.utils.ApiResult<?>
     * @Author: kl
     * @Date: 2020-03-06
     */
    @PostMapping("/addExpert")
    @Log("api小程序端-专家申请接口")
    @ApiOperation(value = "api小程序端-专家申请接口", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @RequiresAuthentication
    @Transactional
    @ApiImplicitParams({@ApiImplicitParam(name = TOKEN_TAG, value = TOKEN_TAG, paramType = "header")})
    public ApiResult<?> addExpert(@RequestHeader(value = TOKEN_TAG, required = false) String token, String fileUrl, String email,
                                  String name, String sex, String idNumber, String type, String orgName, String profileId, String dateOfBirth,
                                  String nation, String education, String major, String politicalAffiliation, String officialCapacity, String QQ, String experience, String liveAddress,
                                  String province,String city,String district, String honor) {
        //1.根据token获取用户登录数据
        UserDO user = this.getClientUser(token);
        if (null == user) {
            return ApiResult.invalid();
        }
        MsgTemplateDO msg = msgTemplateService.findOneByKv("type" , 0 , "temp_ip" , 101);
        boolean j = false;

        //2.判断是否存在数据
//        Map map = new HashMap();
//        map.put("type", Integer.parseInt(type));
//        map.put("userId", user.getId());
//        map.put("profileId", Long.parseLong(profileId));
//        Long id = expertsService.selById(map);
//        if (id != null) {
//            //提示已申请
//            return ApiResult.build(ApiEnumError.EnrolmentError.getCode(), "已申请");
//        }
        ExpertsDO expertsDO = expertsService.findOneByKv("type",Integer.parseInt(type),"user_id",user.getId(),"profile_id", Long.parseLong(profileId));
        boolean isInsert=false;
        if (expertsDO != null) {
            if(expertsDO.getState()!=6) {
                //提示已申请
                return ApiResult.build(ApiEnumError.EnrolmentError.getCode(), "已申请");
            }
        }else{
            expertsDO = new ExpertsDO();
            isInsert=true;
        }

        //3.新建专家表实体，传入基本信息
        //ExpertsDO expertsDO = new ExpertsDO();

        if(user.getOrgId() != null){
            expertsDO.setOrgId(user.getOrgId());
        }else{
            // 2020-03-12新增逻辑-kl
            // 查询判断机构是否在系统内存在： 如不存在，则只在用户表中存入机构信息； 如存在，则存入机构id
            EntityWrapper<OrganizationNewsDO> entityWrapper = new EntityWrapper<>();
            entityWrapper.like("name", orgName);
            List<OrganizationNewsDO> organizationNewsDOList = organizationNewsService.selectList(entityWrapper);
            if (CollectionUtils.isEmpty(organizationNewsDOList)) { // 无机构，则机构信息错误
                return ApiResult.build(ApiEnumError.orgsErr.getCode(), ApiEnumError.orgsErr.getMsg());
            } else if (organizationNewsDOList.size() > 1) { // 多机构，则机构信息不全
                return ApiResult
                        .build(ApiEnumError.orgsIncompleteInfo.getCode(), ApiEnumError.orgsIncompleteInfo.getMsg());
            } else {
                expertsDO.setOrgId(organizationNewsDOList.get(0).getId());//机构id
                user.setOrgId(organizationNewsDOList.get(0).getId());
                j = true;
            }

        }

        expertsDO.setName(name);//专家姓名
        expertsDO.setKpointsId(null);//知识点id
        expertsDO.setType(Integer.parseInt(type));//专家类型
        expertsDO.setApplicantDate(new Date());//申请时间
        expertsDO.setUserId(user.getId());//会员id
        expertsDO.setProfileId(Long.parseLong(profileId));//证书概况id
        expertsDO.setEnclosure(fileUrl);//附件路径
        expertsDO.setHonor(honor);//附件路径
        expertsDO.setState(0);
        boolean b = false;
        if(isInsert) {
            b=expertsService.insert(expertsDO);
        }else{
            b=expertsService.updateById(expertsDO);
        }
        if (b) {
            //4.更新用户表信息
            if(StringUtils.isBlank(user.getName())){
                user.setName(name);//真实姓名
                j = true;
            }

            if(StringUtils.isBlank(user.getOrgName())){
                user.setOrgName(orgName);//所属机构名称
                j = true;
            }
            if(user.getSex() == null){
                user.setSex(Long.parseLong(sex));//性别
                j = true;
            }else if(user.getSex() == 0){
                user.setSex(Long.parseLong(sex));//性别
                j = true;
            }

            if(StringUtils.isBlank(user.getIdNumber())){
                user.setIdNumber(idNumber);//身份证号码
                j = true;
            }
            if(StringUtils.isBlank(user.getNation())){
                user.setNation(nation);//民族
                j = true;
            }
            if(StringUtils.isBlank(user.getEducation())){
                user.setEducation(education);//学历
                j = true;
            }
            if(StringUtils.isBlank(user.getMajor())){
                user.setMajor(major);//专业
                j = true;
            }
            if(StringUtils.isBlank(user.getPoliticalAffiliation())){
                user.setPoliticalAffiliation(politicalAffiliation);//政治面貌
                j = true;
            }
            if(StringUtils.isBlank(user.getOfficialCapacity())){
                user.setOfficialCapacity(officialCapacity);//职务职称
                j = true;
            }
            if(StringUtils.isBlank(user.getQQ())){
                user.setQQ(QQ);//QQ
                j = true;
            }
            if(StringUtils.isBlank(user.getEmail())){
                user.setEmail(email);//邮箱
                j = true;
            }
            if(StringUtils.isBlank(user.getExperience())){
                user.setExperience(experience);//学习、工作经历
                j = true;
            }
            if(StringUtils.isBlank(user.getLiveAddress())){
                user.setLiveAddress(liveAddress);//通讯地址
                j = true;
            }
            if(StringUtils.isBlank(user.getProvince())){
                user.setProvince(province);//省份
                j = true;
            }
            if(StringUtils.isBlank(user.getCity())){
                user.setCity(city);//市
                j = true;
            }
            if(StringUtils.isBlank(user.getDistrict())){
                user.setDistrict(district);//区
                j = true;
            }

            if(StringUtils.isBlank(user.getDateOfBirth())){
                user.setDateOfBirth(dateOfBirth);//出生年月
            }

            if(j){
                List<Long> roleIds = userRoleService.listRoleId(user.getId());
                if (roleIds != null && roleIds.size() > 0) {
                    user.setroleIds(roleIds);
                } else {
                    List<Long> list = new ArrayList<>();
                    list.add(56L);
                    user.setroleIds(list);
                }
                boolean c = userService.updateById(user);
                if (c) {
                    return ApiResult.success(msg.getCode());
                } else {
                    expertsDO.setState(6);
                    expertsService.updateById(expertsDO);
                    return ApiResult.fail();
                }
            }else{
                return ApiResult.success(msg.getCode());
            }
        } else {
            return ApiResult.fail();
        }
    }

    /**
     * api小程序端-专家申请接口
     *
     * @Description: 专家信息申请，填入数据库；参数：Token令牌，专家照片，附件路径，邮箱，专家姓名，专家性别，专家身份证号，专家类型，所属单位，知识点Id，
     * 证书概况id，出生年月，民族，学历，专业，政治面貌，职务职称，QQ，学习、工作经历，现居住地,省份，市，区
     * @Param: [token, imgUrl, fileUrl, email, name, sex, idNumber, type, orgName, kpointsId,
     * profileId, dateOfBirth,nation, education, major, politicalAffiliation, officialCapacity, QQ, experience, liveAddress,province，city，district]
     * @return: com.jinzhi.common.utils.ApiResult<?>
     * @Author: kl
     * @Date: 2020-03-06
     */
    @PostMapping("/saveCaoExpert")
    @Log("api小程序端-专家申请接口")
    @ApiOperation(value = "api小程序端-专家申请接口", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @RequiresAuthentication
    @Transactional
    @ApiImplicitParams({@ApiImplicitParam(name = TOKEN_TAG, value = TOKEN_TAG, paramType = "header")})
    public ApiResult<?> saveCaoExpert(@RequestHeader(value = TOKEN_TAG, required = false) String token, String fileUrl, String email,
                                  String name, String sex, String idNumber, String type, String orgName, String profileId, String dateOfBirth,
                                  String nation, String education, String major, String politicalAffiliation, String officialCapacity, String QQ, String experience, String liveAddress,
                                  String province,String city,String district, String honor) {
        //1.根据token获取用户登录数据
        UserDO user = this.getClientUser(token);
        if (null == user) {
            return ApiResult.invalid();
        }
        MsgTemplateDO msg = msgTemplateService.findOneByKv("type" , 0 , "temp_ip" , 101);
        boolean isInsert=false;

        //2.判断是否存在数据
//        Map map = new HashMap();
//        map.put("type", Integer.parseInt(type));
//        map.put("userId", user.getId());
//        map.put("profileId", Long.parseLong(profileId));
//        Long id = expertsService.selById(map);
        ExpertsDO expertsDO = expertsService.findOneByKv("type",Integer.parseInt(type),"user_id",user.getId(),"profile_id", Long.parseLong(profileId));
        if (expertsDO != null) {
            if(expertsDO.getState()!=6) {
                //提示已申请
                return ApiResult.build(ApiEnumError.EnrolmentError.getCode(), "已申请");
            }
        }else{
            expertsDO = new ExpertsDO();
            isInsert=true;
        }

        //3.新建专家表实体，传入基本信息
      //  ExpertsDO expertsDO = new ExpertsDO();

        if(user.getOrgId() != null){
            expertsDO.setOrgId(user.getOrgId());
        }else{
            // 2020-03-12新增逻辑-kl
            // 查询判断机构是否在系统内存在： 如不存在，则只在用户表中存入机构信息； 如存在，则存入机构id
            EntityWrapper<OrganizationNewsDO> entityWrapper = new EntityWrapper<>();
            entityWrapper.like("name", orgName);
            List<OrganizationNewsDO> organizationNewsDOList = organizationNewsService.selectList(entityWrapper);
            if (CollectionUtils.isEmpty(organizationNewsDOList)) { // 无机构，则机构信息错误
                return ApiResult.build(ApiEnumError.orgsErr.getCode(), ApiEnumError.orgsErr.getMsg());
            } else if (organizationNewsDOList.size() > 1) { // 多机构，则机构信息不全
                return ApiResult
                        .build(ApiEnumError.orgsIncompleteInfo.getCode(), ApiEnumError.orgsIncompleteInfo.getMsg());
            } else {
                expertsDO.setOrgId(organizationNewsDOList.get(0).getId());//机构id
                user.setOrgId(organizationNewsDOList.get(0).getId());
            }

        }


            //4.更新用户表信息
            if(StringUtils.isBlank(user.getName())){
                user.setName(name);//真实姓名
            }

            if(StringUtils.isBlank(user.getOrgName())){
                user.setOrgName(orgName);//所属机构名称
            }
            if(user.getSex() == null){
                user.setSex(Long.parseLong(sex));//性别
            }else if(user.getSex() == 0){
                user.setSex(Long.parseLong(sex));//性别
            }

            if(StringUtils.isBlank(user.getIdNumber())){
                user.setIdNumber(idNumber);//身份证号码
            }
            if(StringUtils.isBlank(user.getNation())){
                user.setNation(nation);//民族
            }
            if(StringUtils.isBlank(user.getEducation())){
                user.setEducation(education);//学历
            }
            if(StringUtils.isBlank(user.getMajor())){
                user.setMajor(major);//专业
            }
            if(StringUtils.isBlank(user.getPoliticalAffiliation())){
                user.setPoliticalAffiliation(politicalAffiliation);//政治面貌
            }
            if(StringUtils.isBlank(user.getOfficialCapacity())){
                user.setOfficialCapacity(officialCapacity);//职务职称
            }
            if(StringUtils.isBlank(user.getQQ())){
                user.setQQ(QQ);//QQ
            }
            if(StringUtils.isBlank(user.getEmail())){
                user.setEmail(email);//邮箱
            }
            if(StringUtils.isBlank(user.getExperience())){
                user.setExperience(experience);//学习、工作经历
            }
            if(StringUtils.isBlank(user.getLiveAddress())){
                user.setLiveAddress(liveAddress);//通讯地址
            }
            if(StringUtils.isBlank(user.getProvince())){
                user.setProvince(province);//省份
            }
            if(StringUtils.isBlank(user.getCity())){
                user.setCity(city);//市
            }
            if(StringUtils.isBlank(user.getDistrict())){
                user.setDistrict(district);//区
            }

            if(StringUtils.isBlank(user.getDateOfBirth())){
                user.setDateOfBirth(dateOfBirth);//出生年月
            }

            //if(j){
                List<Long> roleIds = userRoleService.listRoleId(user.getId());
                if (roleIds != null && roleIds.size() > 0) {
                    user.setroleIds(roleIds);
                } else {
                    List<Long> list = new ArrayList<>();
                    list.add(56L);
                    user.setroleIds(list);
                }
                boolean c = userService.updateById(user);
                if (c) {
                    expertsDO.setName(name);//专家姓名
                    expertsDO.setKpointsId(null);//知识点id
                    expertsDO.setType(Integer.parseInt(type));//专家类型
                    expertsDO.setApplicantDate(new Date());//申请时间
                    expertsDO.setUserId(user.getId());//会员id
                    expertsDO.setProfileId(Long.parseLong(profileId));//证书概况id
                    expertsDO.setEnclosure(fileUrl);//附件路径
                    expertsDO.setHonor(honor);//附件路径
                    expertsDO.setState(6);
                    if(isInsert){
                        expertsService.insert(expertsDO);
                    }else{
                        expertsService.updateById(expertsDO);
                    }
                    return ApiResult.success(msg.getCode());
                } else {
                    //expertsService.deleteById(expertsDO.getId());
                    return ApiResult.fail();
                }
           // }else{
           //     return ApiResult.success(msg.getCode());
           // }
    }


    /**
     * api客户端-编辑专家信息接口
     *
     * @Description: 编辑专家信息 ，参数：tonken令牌，专家类型，知识点id（多id，逗号拼接），证书概况id，附件路径
     * @Param: [token, expertId, type, kpointsId, profileId, enclosure]
     * @return: com.jinzhi.common.utils.ApiResult<?>
     * @Author: kl
     * @Date: 2020-03-13
     */
    @PostMapping("/editExpert")
    @Log("api客户端-编辑专家信息接口")
    @ApiOperation("api客户端-编辑专家信息接口")
    @RequiresAuthentication
    @Transactional
    @ApiImplicitParams({@ApiImplicitParam(name = TOKEN_TAG, value = TOKEN_TAG, paramType = "header")})
    public ApiResult<?> editExpert(@RequestHeader(value = TOKEN_TAG, required = false) String token, String expertId, String type, String profileId,
                                   String enclosure, String honor) {
        //1.根据token获取用户登录数据
        UserDO user = this.getClientUser(token);
        if (null == user) {
            return ApiResult.invalid();
        }
        Map map = new HashMap();
        MsgTemplateDO msg = msgTemplateService.findOneByKv("type" , 0 , "temp_ip" , 101);
        if (msg != null){
            map.put("tempId" , msg.getCode());
        }else {
            map.put("tempId" , null);
        }
        if (StringUtils.isNotBlank(expertId)) {
            ExpertsDO expertsDO = expertsService.selectById(expertId);
            if (expertsDO != null) {
                expertsDO.setType(Integer.parseInt(type));
                expertsDO.setKpointsId(null);
                expertsDO.setProfileId(Long.parseLong(profileId));
                 expertsDO.setHonor(honor);
                expertsDO.setState(0);//编辑专家信息代表审核未通过，状态需要改成待审核
                //判断用户表的组织id是否为空，如果不为空，则更新至专家表
                if (user.getOrgId() != null) {
                    expertsDO.setOrgId(user.getOrgId());
                }
                expertsDO.setEnclosure(enclosure);//专家附件

                boolean b = expertsService.updateById(expertsDO);
                if (!b) {
                    return ApiResult.build(ApiEnumError.EDITERR.getCode(), ApiEnumError.EDITERR.getMsg());
                }
            }
        }

        return ApiResult.success(map);
    }


    /**
     * api小程序端-专家信息详情查询接口
     *
     * @Description: 查询专家信息详情，参数：验证token，专家信息id
     * @Param: [token, expertId]
     * @return: com.jinzhi.common.utils.ApiResult<?>
     * @Author: kl
     * @Date: 2020-03-13
     */
    @GetMapping("/selExpertsDetail")
    @Log("api客户端-专家信息详情查询接口")
    @ApiOperation("api客户端-专家信息详情查询接口")
    @RequiresAuthentication
    @ApiImplicitParams({@ApiImplicitParam(name = TOKEN_TAG, value = TOKEN_TAG, paramType = "header")})
    public ApiResult<?> selExpertsDetail(@RequestHeader(value = TOKEN_TAG, required = false) String token, String expertId) {
        //1.根据token获取用户登录数据
        UserDO user = this.getClientUser(token);
        if (null == user) {
            return ApiResult.invalid();
        }
        Map map = new HashMap();
        ExpertsDO expertsDO = expertsService.selectById(Long.parseLong(expertId));
        if (expertsDO != null) {
            map.put("profileId", expertsDO.getProfileId());
            map.put("kpointsId", expertsDO.getKpointsId());
            map.put("type", expertsDO.getType());
            map.put("enclosure", expertsDO.getEnclosure());
            map.put("honor", expertsDO.getHonor());

        } else {
            map.put("profileId", "");
            map.put("kpointsId", "");
            map.put("type", "");
            map.put("enclosure", "");
            map.put("honor", "");
        }
        return ApiResult.success(map);
    }

}
